import os
import imp
import marshal

class module:
	def __init__(self, parent):
		self.parent = parent

		self.events = ["onPrivmsg"]
		self.metadata = {
        "name":"Alice",
        "description":"Alice Bot",
        "author":"Samuel Gordalina",
        "email":"samuel.gordalina@gmail.com",
        "version":"0.1",
        "required_version":(0,1)
		}

		# Load PyAIML
		fp, pathname, description = imp.find_module("PyAIML", ["modules/alice/"])
		aiml = imp.load_module("PyAIML", fp, pathname, description)

		self.kernel = aiml.Kernel()
		self.kernel.verbose(True)
		self.sessionsDir = "modules/alice/sessions"
		self.brain = "modules/alice/fanhoso.brain"

		if os.path.isfile(self.brain):
			self.kernel.bootstrap(brainFile=self.brain)
		else:
			self.kernel.setPredicate("secure", "yes")
			self.kernel.bootstrap(learnFiles="modules/alice/std-startup.xml", commands="bootstrap")
			self.kernel.setPredicate("secure", "no")
			self.kernel.saveBrain(self.brain)

		try:
			for session in os.listdir(self.sessionsDir):
				root, ext = os.path.splitext(session)
				if ext != ".ses":
					# This isn't a session file.
					continue
				# Load the contents of the session file (a single dictionary
				# containing all the predicates for this session).
				f = file("%s/%s" %(self.sessionsDir, session), "rb")
				d = marshal.load(f)
				f.close()
				# update the predicate values in the Kernel.
				for k,v in d.items():
					self.kernel.setPredicate(k,v,root)
		except OSError:
			print "WARNING: Error loading session data from", sessionsDir

		self.kernel.setBotPredicate("name", "fanhoso")
		self.kernel.setBotPredicate("master", "thoth")

	def respond(self, input, session):
		response = self.kernel.respond(input, session) 
		try:
			if not os.path.isdir(self.sessionsDir): os.mkdir(self.sessionsDir)
			sessionfile = file("%s/%s.ses" % (self.sessionsDir, session), "wb")
			marshal.dump(self.kernel.getSessionData(session), sessionfile)
			sessionfile.close()
		except KeyError:
			pass
		return response

	def onPrivmsg(self, src, message, channel=""):
		if channel != "" and self.parent.irc.ircNick in message.split(" ")[0]:
			nick = src.split("!")[0]
			message = "".join(message[(len(message.split(" ")[0]) +1):])
			response = self.respond(message, nick)
			if response != "":
				self.parent.irc.privmsg(channel, nick + ": " + response) 

